// packageE/community_buying/addinfo/addinfo.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    business_hours_start: "00:00",
    business_hours_end: "24:00",

    imageList: [],

    imagefile1: "",
    imagefile2: "",
    imagefile3: "",

    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],

    realname: "",
    deliver_name: "",
    deliver_mobile: "",
    address: "",
    full_address: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //加载地址数据初始化
    this._initAddressInfo();
    this.getData();
  },
  getData() {
    let urlStr = app.getNetAddresss(
      "plugin.package-deliver.frontend.deliver.editDeliver"
    );
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        console.log(res);
        if (res.result != 1) {
          return false;
        }
        let deliver = res.data.deliver;

        let realname = deliver.realname;
        let deliver_name = deliver.deliver_name;
        let deliver_mobile = deliver.deliver_mobile;
        let address = deliver.address;
        let full_address = deliver.full_address;
        let imageList = deliver.thumb;
        let tempImageList = JSON.parse(JSON.stringify(imageList));
        let imagefile1 = deliver.aptitute;
        let imagefile2 = deliver.id_card_front;
        let imagefile3 = deliver.id_card_side;
        let business_hours_start = deliver.business_hours_start;
        let business_hours_end = deliver.business_hours_end;
        let apply = {};
        apply.province_id = deliver.province_id;
        apply.city_id = deliver.city_id;
        apply.district_id = deliver.district_id;
        apply.street_id = deliver.street_id;

        this.setData({
          realname,
          deliver_name,
          deliver_mobile,
          address,
          full_address,
          imageList,
          imagefile1,
          imagefile2,
          tempImageList,
          imagefile3,
          business_hours_start,
          business_hours_end,
          apply,
        });
        this.selseadress();
        if (apply.district_id && apply.district_id != 0) {
          this.setData({ strShow: true });
          this.bj_getStreet(apply.district_id);
        }
      },
    });
  },
  pushData() {
    let {
      realname,
      deliver_name,
      deliver_mobile,
      address,
      // full_address,
      apply,
      business_hours_start,
      business_hours_end,
    } = this.data;
    let thumb = this.data.imageList;
    let aptitute = this.data.imagefile1;
    let id_card_front = this.data.imagefile2;
    let id_card_side = this.data.imagefile3;
    let province_id = apply.province_id;
    let city_id = apply.city_id;
    let district_id = apply.district_id;
    let street_id = apply.street_id;
    if (app._isTextEmpty(realname)) return this.tips("姓名不能为空");
    if (app._isTextEmpty(deliver_name)) return this.tips("提货卡不能为空");
    if (app._isTextEmpty(deliver_mobile)) return this.tips("提货卡不能为空");
    if (app._isTextEmpty(address)) return this.tips("详细地址不能为空");
    if (thumb.length < 0) return this.tips("请上传自提点图片");
    let urlStr = app.getNetAddresss(
      "plugin.package-deliver.frontend.deliver.editDeliver"
    );
    let deliver = {
      realname,
      deliver_name,
      deliver_mobile,
      address,
      business_hours_start,
      business_hours_end,
      thumb,
      aptitute: aptitute,
      id_card_front,
      id_card_side,
      province_id,
      city_id,
      district_id,
      street_id,
    };
    app._postNetWork({
      url: urlStr,
      data: {
        deliver,
      },
      success: (resdata) => {
        var res = resdata.data;
        console.log(res);
        if (res.result != 1) {
          return this.tips(res.msg);
        }
        wx.navigateBack();
      },
    });
  },
  // 选择地址
  // 处理地址
  selseadress() {
    let provinceData = wx.getStorageSync("provinceData");
    let cityData = wx.getStorageSync("cityData");
    let districtData = wx.getStorageSync("districtData");
    console.log(this.data.form);
    console.log(provinceData);
    let province = "";
    let city = "";
    let district = "";
    for (let i in provinceData) {
      if (provinceData[i].id == this.data.apply.province_id) {
        province = provinceData[i].areaname;
      }
    }
    for (let i in cityData) {
      if (cityData[i].id == this.data.apply.city_id) {
        city = cityData[i].areaname;
      }
    }
    for (let i in districtData) {
      if (districtData[i].id == this.data.apply.district_id) {
        district = districtData[i].areaname;
      }
    }
    let addressName = `${province}${city}${district}`;
    this.setData({
      addressName,
    });
  },
  //编辑的时候获取街道
  bj_getStreet(param) {
    console.log(param);
    var that = this;
    let urlStr = app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + param;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1 && !app._isTextEmpty(res.data)) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            for (let i = 0; i < res.data.length; i++) {
              console.log(that.data.apply.street_id);
              if (res.data[i].id == that.data.apply.street_id) {
                that.setData({
                  street: res.data[i].areaname,
                  districtVal: res.data,
                });
                console.log(res.data[i].areaname);
              }
            }
          } else {
            that.setData({
              strShow: false,
            });
          }
        } else {
          that.setData({
            strShow: false,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  onRead_1(evt) {
    let index = evt.currentTarget.dataset.index;
    let that = this;
    let urlStr = app.getNetAddresss("upload.uploadPic");
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths[0]);
        // wx.compressImage({
        // 	src: tempFilePaths[0], // 图片路径
        // 	quality: 60, // 压缩质量
        // 	success(e) {
        let photourl = tempFilePaths[0];
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: "file",
          success(resdata) {
            var res = JSON.parse(resdata.data);
            if (res.result != 1) {
              wx.showToast({
                icon: "none",
                title: res.msg,
                duration: 1500,
              });
              return false;
            }
            let target = "imagefile" + index;
            that.setData({
              [target]: res.data.img_url,
            });
          },
        });
        // },
        // fail(e) {

        // },
        // complete(e) {

        // }
        // })
      },
    });
  },

  treetShowLeft() {
    this.setData({
      streetShow: false,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  addressShowbtn() {
    this.setData({
      addressShow: true,
    });
  },

  bindStartTimeChange(evt) {
    console.log(evt.detail.value);
    this.setData({
      business_hours_start: evt.detail.value,
    });
  },

  bindEndTimeChange(evt) {
    this.setData({
      business_hours_end: evt.detail.value,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  // 其他图片
  onRead_6() {
    wx.chooseImage({
      count: 9,
      sizeType: ["compressed"],
      sourceType: ["album", "camera"],
      success: (res) => {
        // var tempFilePaths = res.tempFilePaths
        this.unload(
          {
            tempFilePaths: res.tempFilePaths,
          },
          6
        );
      },
    });
  },
  // 营业执照
  onRead_5() {
    wx.chooseImage({
      count: 9,
      sizeType: ["compressed"],
      sourceType: ["album", "camera"],
      success: (res) => {
        // var tempFilePaths = res.tempFilePaths
        this.unload(
          {
            tempFilePaths: res.tempFilePaths,
          },
          5
        );
      },
    });
  },
  //多张上传方法
  unload(data, index) {
    let urlStr = app.getNetAddresss("upload.uploadPic");
    var i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: urlStr,
      filePath: data.tempFilePaths[i],
      name: "file",
      formData: null,
      success: (resdata) => {
        var res = JSON.parse(resdata.data);
        if (res.result != 1) {
          fail++;
          return this.tips(res.msg);
        }
        if (index == 5) {
          this.data.imagefile1.push(res.data.img_url);
          this.setData({
            imagefile1: this.data.imagefile1,
          });
        } else if (index == 6) {
          this.data.imageList.push(res.data.img_url);
          this.setData({
            imageList: this.data.imageList,
          });
        }
      },
      fail(e) {
        fail++;
      },
      complete(e) {
        i++;
        if (i == data.tempFilePaths.length) {
          //当图片传完时，停止调用
          console.log("执行完毕");
          console.log("成功：" + success + " 失败：" + fail);
        } else {
          //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          this.unload(data, index); //递归，回调自己
        }
      },
    });
  },

  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2],
    });
    this._initAddressInfo();
  },
  // 关闭选择收货地址
  _closeDateLw: function () {
    this.setData({
      addressShow: false,
    });
  },
  streetShowbtn() {
    this.setData({
      streetShow: true,
    });
  },
  streetConfirm(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      street: item.areaname,
      "apply.street_id": item.id,
      streetShow: false,
    });
  },
  //城市结果
  resultAdd: function () {
    let seleData = this.data.selectAddressData;
    let retCity =
      seleData[0].name + " " + seleData[1].name + " " + seleData[2].name;
    this.setData({
      addressName: retCity,
      provice: seleData[0].name,
      city: seleData[1].name,
      district: seleData[2].name,
    });
    this.setData({
      "apply.province_id": seleData[0].id,
      "apply.city_id": seleData[1].id,
      "apply.district_id": seleData[2].id,
      addressShow: false,
    });
    this.getStreet(seleData[2].id);
  },
  //获取街道
  getStreet(param) {
    let that = this;
    let urlStr = "";
    urlStr += app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + param;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            that.setData({
              districtVal: res.data,
              strShow: true,
            });
          } else {
            that.setData({
              strShow: false,
            });
          }
        } else {
          that.setData({
            strShow: false,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地址信息准备就绪");
        that._getProvinceData();
      },
      fail: function (res) {
        console.log("省fail");
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: "provinceData",
              data: province,
            });
            wx.setStorage({
              key: "cityData",
              data: city,
            });
            wx.setStorage({
              key: "districtData",
              data: district,
            });
            that._initAddressInfo();
          },
          fail: function (res) {},
          state: true,
        });
      },
    });
  },
  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("省读取成功", res.data);
        that.setData({
          provinceData: res.data,
        });
        that.setData({
          "selectAddressData[0].name":
            res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0],
        });
        that._getCityData();
      },
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    console.log("城市", "_data", _data);
    var that = this;
    var _keyName = "cityData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("城市读取成功", res);

        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("城市数据筛选", _json);
        that.setData({
          cityData: _json,
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1],
        });
        that._getDistrictData();
      },
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    console.log("地区", "_data", _data);
    console.log(_data);
    var that = this;
    var _keyName = "districtData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地区读取成功");
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("地区数据筛选", _json);
        that.setData({
          districtData: _json,
        });
        console.log("districtData", _json);
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2],
        });
        console.log("over", that.data.selectAddressData);
      },
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},
  tips(msg) {
    wx.showToast({
      title: msg,
      icon: "none",
    });
    return false;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  delIntu_6(e) {
    var delpaths = this.data.imageList;
    let del = e.currentTarget.id;
    delpaths.splice(del, 1);
    this.setData({
      imageList: delpaths,
    });
  },

  delIntu_5(e) {
    var delpaths = this.data.imagefile1;
    let del = e.currentTarget.id;
    delpaths.splice(del, 1);
    this.setData({
      imagefile1: delpaths,
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
